#include "IndirectionTwee.h"
#include "IndirectionEen.h"
#include <cassert>

IndirectionTwee::IndirectionTwee(FileSystem* filesystem, byte *bytes) : Indirection(filesystem, bytes) {
	int j = 0;
    for (int i = 0; i < INDSIZ; ++i) {
	    blocklist[i] = getlong(bytes, j);
	    j += 4;
    }
}

IndirectionTwee::~IndirectionTwee() {
}

long IndirectionTwee::getBlocknummer(int relative_block_position) {
    int offset = relative_block_position % INDSIZ;
    assert(offset >= 0);
    assert(offset <= INDSIZ);

    int position_indirection1 = (relative_block_position - offset) / INDSIZ;
    assert(position_indirection1 >= 0);
    assert(position_indirection1 <= INDSIZ);

    long address_indirection1 = blocklist[position_indirection1];

    if (address_indirection1 == 0) return -1;
    Blok* indirection1_block = filesystem->getBlok(address_indirection1);

	byte* bytes_temp = indirection1_block->getBytes();
	byte bytes[DBLKSIZ];
	for (int i = 0; i < DBLKSIZ; ++i) {
		bytes[i] = bytes_temp[i];
	}

    IndirectionEen* indirection1 = new IndirectionEen(filesystem, bytes); // TODO delete instantie van object

    long blocknummer = indirection1->getBlocknummer(offset);

   	//delete bytes_temp;
    delete indirection1;
    indirection1 = 0;

    return blocknummer;
}
